package org.dreamwork.cai.spring;

import org.dreamwork.concurrent.broadcast.ILocalBroadcastReceiver;
import org.dreamwork.concurrent.broadcast.ILocalBroadcastService;
import org.dreamwork.concurrent.broadcast.LocalBroadcaster;
import org.dreamwork.concurrent.broadcast.LocalMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;

/**
 * 本地广播服务在 Spring 中的桥接器
 */
@Service
public class SpringLocalBroadcastBridge implements ILocalBroadcastService {
    private final LocalBroadcaster shadow;

    /**
     * 本地广播服务在 Spring 中的桥接器.
     *
     * <p>这个线程池在 Spring 启动时创建，请参见 {@link SpringBridge#createExecutor()}</p>
     *
     * @param executor 本地广播所需的线程池
     */
    public SpringLocalBroadcastBridge (@Autowired ExecutorService executor) {
        shadow = new LocalBroadcaster (executor);
        executor.execute (shadow);
    }

    @Override
    public void register (String category, ILocalBroadcastReceiver receiver) {
        if (shadow != null)
            shadow.register (category, receiver);
    }

    @Override
    public void unregister (String category, ILocalBroadcastReceiver receiver) {
        if (shadow != null)
            shadow.unregister (category, receiver);
    }

    @Override
    public void broadcast (String category, LocalMessage message) {
        if (shadow != null)
            shadow.broadcast (category, message);
    }

    public void shutdown () {
        if (shadow != null) {
            shadow.shutdown ();
        }
    }
}
